package com.alxy.day1.repository;

import com.alxy.day1.entity.Product;
import com.alxy.day1.entity.User;
import jakarta.persistence.LockModeType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

/**
 * @author 爱莉希雅
 * @version java 17
 */
@SuppressWarnings({"all"})
@Repository
public interface ProductRepository extends JpaRepository<Product,Long> {
    // 乐观锁更新库存
    @Modifying
    @Query("UPDATE Product p SET p.stock = p.stock - :quantity WHERE p.productId = :id AND p.stock >= :quantity and p.version=:version")
    int updateStockOptimistically(@Param("id") Long id, @Param("quantity") int quantity,@Param("version") int version);

    // 悲观锁查询商品
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT p FROM Product p WHERE p.productId= :id")
    Product findByIdWithPessimisticLock(@Param("id") Long id);


    @Override
    <S extends Product> S save(S entity);
}
